/*
* createTime：2019/4/29
* author：junyong.hong
* description:
*/
<template>
  <div class="">
    <dl class="m-categroy">
      <dt>按拼音首字母选择：</dt>
      <dd
        v-for="item in list"
        :key="item">
        <a :href="'#city-'+item">{{ item }}</a>
      </dd>
    </dl>
    <dl
      v-for="item in block"
      :key="item.title"
      class="m-categroy-section">
      <dt :id="'city-'+item.title">{{ item.title }}</dt>
      <dd>
        <span
          v-for="c in item.city"
          :key="c">{{ c }}</span>
      </dd>
    </dl>
  </div>
</template>

<script>
  import pyjs from 'js-pinyin'

  export default {
    data() {
      return {
        list: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split(''),
        block: []
      }
    },
    async mounted() {
      let self = this;
      let blocks = []
      let {status, data: {city}} = await self.$axios.get('/geo/city');
      if (status === 200) {
        let p
        let c
        let d = {}
        city.forEach(item => {
          // 获取拼音首字母
          p = pyjs.getFullChars(item.name).toLocaleLowerCase().slice(0, 1)
          // 首字母的值
          c = p.charCodeAt(0)

          if (c > 96 && c < 123) {
            // 如果没有值，申明一个数组
            if (!d[p]) {
              d[p] = []
            }

            // 往数组里添加参数
            d[p].push(item.name)
          }
        })
//        a:["鞍山市", "安庆市", "安阳市", "阿拉善盟"]
//        console.log('ddd', d)

//        0: "a"
//        1: ["鞍山市", "安庆市", "安阳市", "阿拉善盟"]
//        console.log('ddd', Object.entries(d))

        // 遍历d对象
        for (let [k, v] of Object.entries(d)) {
          blocks.push({
            title: k.toUpperCase(),
            city: v
          })
        }

        // blocks按字母排序
        blocks.sort((a, b) => a.title.charCodeAt(0) - b.title.charCodeAt(0))

        self.block = blocks
      }
    }
  }
</script>

<style lang="scss">
  @import "@/assets/css/changeCity/categroy.scss";
</style>
